package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.album.service.AlbumStatService;
import com.atguigu.tingshu.model.album.AlbumStat;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 专辑统计服务实现类
 */
@Slf4j
@Service
public class AlbumStatServiceImpl implements AlbumStatService {

    @Autowired
    private AlbumStatMapper albumStatMapper;

    /**
     * 更新专辑统计信息
     *
     * @param albumId  专辑ID
     * @param statType 统计类型
     * @param count    更新数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAlbumStat(Long albumId, String statType, Integer count) {
        log.info("开始更新专辑统计 - AlbumId: {}, StatType: {}, Count: {}", albumId, statType, count);

        // 查询是否已存在统计记录
        LambdaQueryWrapper<AlbumStat> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlbumStat::getAlbumId, albumId)
                .eq(AlbumStat::getStatType, statType);
        AlbumStat albumStat = albumStatMapper.selectOne(queryWrapper);

        if (albumStat == null) {
            // 不存在则新增
            albumStat = new AlbumStat();
            albumStat.setAlbumId(albumId);
            albumStat.setStatType(statType);
            albumStat.setStatNum(count);
            albumStatMapper.insert(albumStat);
            log.info("新增专辑统计记录 - AlbumId: {}, StatType: {}, StatNum: {}", albumId, statType, count);
        } else {
            // 已存在则更新（累加）
            albumStat.setStatNum(albumStat.getStatNum() + count);
            albumStatMapper.updateById(albumStat);
            log.info("更新专辑统计记录 - AlbumId: {}, StatType: {}, NewStatNum: {}", albumId, statType, albumStat.getStatNum());
        }

        // TODO: 同步更新 ES 中的专辑统计信息（发送消息到 ES 更新队列）
    }
}
